import React, { useContext } from 'react';
import { useParams, Link } from 'react-router-dom/cjs/react-router-dom.min';
import { useState, useEffect } from 'react';
import api from './api/api';
import DescriptionCard from './DescriptionCard';
import DataContext from './context/DataContext';
import { useHistory } from 'react-router-dom/cjs/react-router-dom';
import placeholder from './assets/placeholder_240x240.png';

const Podcast = () => {

  const history = useHistory();
  const { baseUrl, loginUserId } = useContext(DataContext);
  const { id } = useParams();
  const [podcast, setPodcast] = useState({});
  const [author, setAuthor] = useState({});
  const [episodes, setEpisodes] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  let counter = 0;

  const handleEdit = () => {
    history.push(`/edit-podcast/${id}`);
  };

  const handlePost = () => {
    history.push(`/podcasts/${id}/post-episode`);
  };

  useEffect(() => {
    const fetchPodcast = async () => {
      try {
        const podcastResponse = await api.get(`/podcasts/${id}`);
        const returnedPodcast = podcastResponse.data;
        returnedPodcast.coverUrl = `${baseUrl}/podcasts/${returnedPodcast.id}/cover`;
        setPodcast(returnedPodcast);
        const authorResponse = await api.get(`/users/${returnedPodcast.author_id}`);
        const returnedAuthor = authorResponse.data;
        setAuthor(returnedAuthor);
        const episodesResponse = await api.get(`/podcasts/${returnedPodcast.id}/episodes`);
        const returnedEpisodes = episodesResponse.data.reverse();
        setEpisodes(returnedEpisodes);
        setIsLoading(false);
      }
      catch (err) {
        console.log(`Error:${err.message}`);
      }
    };
    fetchPodcast();
  }, [id, baseUrl]);

  return (
    <div className='
        container
        min-h-100
        flex-fill'
    >
      <div className="container">

        <h1 className='mt-2 mb-5'>播客详情</h1>

        {!isLoading &&

          <div className="row">

            <div className="col-lg-4 col-sm d-flex justify-content-center align-items-center">
              <img src={podcast.coverUrl} onError={(e) => e.target.src = placeholder} className="img-thumbnail mb-3" alt="..." />
            </div>

            <div className='col-lg-7 col-sm text-center d-flex flex-column justify-content-center align-items-end'>
              <table className="table table-bordered table-hover">
                <tbody>
                  <tr>
                    <th scope="row">名称</th>
                    <td>{podcast.title}</td>
                  </tr>
                  <tr>
                    <th scope="row">作者</th>
                    <td><Link className="text-decoration-none" to={`/users/${author.id}`}>{author.nickname}</Link></td>
                  </tr>
                  <tr>
                    <th scope="row">分类</th>
                    <td>{podcast.itunes_category}</td>
                  </tr>
                  <tr>
                    <th scope="row">创建时间</th>
                    <td>{podcast.createtime}</td>
                  </tr>
                  <tr>
                    <th scope="row">Feed URL</th>
                    <td>{`${baseUrl}/podcasts/${id}/rss`}</td>
                  </tr>
                </tbody>
              </table>
              {loginUserId === author.id &&
                <div>
                  <button className="btn btn-sm btn-outline-primary mx-1" onClick={handlePost}>新建</button>
                  <button className="btn btn-sm btn-outline-primary mx-1" onClick={handleEdit}>编辑</button>
                </div>
              }
            </div>
            <h2 className='my-3'>简介</h2>
            <DescriptionCard text={podcast.description} />
          </div>
        }
        <div className="my-3"></div>

        <div className="row text-center">
          <table className="table table-hover">
            <thead>
              <tr>
                <th scope='col'>#</th>
                <th scope='col'>标题</th>
                <th scope='col'>时长</th>
                <th scope='col'>日期</th>
              </tr>
            </thead>
            <tbody>
              {episodes.map((episode) => (
                <tr key={episode.id}>
                  <td>{episodes.length - counter++}</td>
                  <td><Link className="text-decoration-none" to={`/episodes/${episode.id}`}>{episode.title}</Link></td>
                  <td>{episode.duration}</td>
                  <td>{episode.pub_date.slice(0, 16)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

      </div>

    </div >
  );
};

export default Podcast;
